<template>
  <div class="employee-management-container">
    <!-- 头部筛选区（不变） -->
    <div class="header-filter">
      <el-form :model="searchForm" inline label-width="80px" style="font-weight: bold">
        <el-form-item label="工号">
          <el-input v-model="searchForm.workId" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="searchForm.department" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="入职时间">
          <el-date-picker
              v-model="searchForm.entryTime"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="batch-operation">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        <el-dropdown @command="handleBatchOperate">
          <el-button type="info" icon="ArrowDown">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="batchDelete">批量删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 新增/编辑弹窗（不变） -->
    <el-dialog
        title="新增员工"
        v-model="dialogVisible"
        width="600px"
        :lock-scroll='false'
    >
      <el-form
          :model="form"
          ref="formRef"
          label-width="100px"
      >
        <el-form-item label="工号">
          <el-input v-model="form.work_id" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="部门">
          <el-input v-model="form.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="form.id_number" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="学历">
          <el-select v-model="form.degree" placeholder="请选择学历">
            <el-option label="本科" value="本科" />
            <el-option label="专科" value="专科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士" value="博士" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="入职时间">
          <el-date-picker
              v-model="form.entry_time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="合同期限">
          <el-date-picker
              v-model="form.contract_term"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="在职" value="在职" />
            <el-option label="离职" value="离职" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 数据表格（显示分页后的数据） -->
    <el-table
        :data="paginatedData"
    border
    stripe
    :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 500 }"
    @selection-change="handleSelectionChange"
    style="font-weight: bold"
    >
    <!-- 表格列不变 -->
    <el-table-column type="selection" width="55" />
    <el-table-column label="部门" prop="department" width="115" align="center" />
    <el-table-column label="工号" prop="work_id" width="80" align="center" />
    <el-table-column label="姓名" prop="name" width="80" align="center" />
    <el-table-column label="身份证号" prop="id_number" width="200" align="center" />
    <el-table-column label="学历" prop="degree" width="100" align="center" />
    <el-table-column label="职位" prop="position" width="120" align="center" />
    <el-table-column label="性别" prop="gender" width="80" align="center" />
    <el-table-column label="手机号" prop="phone" width="140" align="center" />
    <el-table-column label="邮箱" prop="email" width="200" align="center" />
    <el-table-column label="入职时间" prop="entry_time" width="160" align="center" />
    <el-table-column label="合同期限" prop="contract_term" width="160" align="center" />
    <el-table-column label="状态" prop="status" align="center" width="160">
      <template #default="scope">
        <el-tag :type="scope.row.status === '在职' ? 'success' : 'danger'">
          {{ scope.row.status }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center" width="220">
      <template #default="scope">
        <el-button type="primary" icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
        <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[12, 12, 12]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    style="margin-top: 20px;display: flex;justify-content: center"
    ></el-pagination>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowDown, Edit, Delete, Plus } from '@element-plus/icons-vue';
import axios from 'axios';

// 后端基础地址
const API_BASE_URL = 'http://localhost:8000/api';


const searchForm = reactive({
  workId: '',
  name: '',
  phone: '',
  department: '',
  entryTime: [],
});

const allData = ref([]);  // 全量数据（一次性加载）
const filteredData = ref([]);  // 筛选后的全量数据
const paginatedData = computed(() => {  // 计算当前页数据
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filteredData.value.slice(startIndex, endIndex);
});

const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(12);
const selectedRows = ref([]);
const dialogVisible = ref(false);
const formRef = ref(null);

// 表单数据
const form = reactive({
  id: '',
  work_id: '',
  name: '',
  department: '',
  id_number: '',
  degree: '',
  position: '',
  gender: '',
  phone: '',
  email: '',
  entry_time: '',
  contract_term: '',
  status: '在职'
});

// 页面加载时获取全量数据（不分页）
onMounted(() => {
  fetchAllData();
});

// 获取全量数据（核心：一次性加载所有数据）
const fetchAllData = async () => {
  try {
    const params = new URLSearchParams();
    if (searchForm.workId) params.append('work_id', searchForm.workId);
    if (searchForm.name) params.append('name', searchForm.name);
    if (searchForm.phone) params.append('phone', searchForm.phone);
    if (searchForm.department) params.append('department', searchForm.department);
    if (searchForm.entryTime && searchForm.entryTime.length === 2) {
      params.append('entry_start', searchForm.entryTime[0]);
      params.append('entry_end', searchForm.entryTime[1]);
    }

    // 后端需返回全量数据
    const response = await axios.get(`${API_BASE_URL}/employees/search/`, { params });
    allData.value = response.data.employees || [];
    filteredData.value = [...allData.value];  // 初始筛选数据=全量数据
    total.value = filteredData.value.length;  // 总条数
    currentPage.value = 1;  // 重置到第一页
  } catch (error) {
    ElMessage.error('获取数据失败，请重试');
    console.error('获取员工数据错误:', error);
  }
};

// 查询（前端筛选全量数据）
const handleSearch = () => {
  // 基于全量数据进行前端筛选
  filteredData.value = allData.value.filter(item => {
    // 工号筛选（模糊匹配）
    if (searchForm.workId && !item.work_id.includes(searchForm.workId)) return false;
    // 姓名筛选（模糊匹配）
    if (searchForm.name && !item.name.includes(searchForm.name)) return false;
    // 手机号筛选（模糊匹配）
    if (searchForm.phone && !item.phone.includes(searchForm.phone)) return false;
    // 部门筛选（模糊匹配）
    if (searchForm.department && !item.department.includes(searchForm.department)) return false;
    // 入职时间范围筛选
    if (searchForm.entryTime && searchForm.entryTime.length === 2) {
      const itemEntryDate = new Date(item.entry_time).toISOString().split('T')[0];
      if (itemEntryDate < searchForm.entryTime[0] || itemEntryDate > searchForm.entryTime[1]) {
        return false;
      }
    }
    return true;
  });
  total.value = filteredData.value.length;  // 更新总条数
  currentPage.value = 1;  // 重置到第一页
};

// 重置筛选条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'entryTime' ? [] : '';
  });
  filteredData.value = [...allData.value];  // 恢复全量数据
  total.value = filteredData.value.length;
  currentPage.value = 1;
  ElMessage.info('查询条件已重置');
};


const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;  // 直接切换页码，前端截取数据
};

// 新增操作（新增后刷新全量数据）
const handleAdd = () => {
  Object.keys(form).forEach(key => {
    form[key] = key === 'status' ? '在职' : '';
  });
  dialogVisible.value = true;
};

const submitForm = async () => {
  try {
    await axios.post(`${API_BASE_URL}/employees/`, form);
    ElMessage.success('新增员工成功');
    dialogVisible.value = false;
    fetchAllData();  // 重新获取全量数据，保证数据最新
  } catch (error) {
    ElMessage.error('新增失败: ' + (error.response?.data?.error || error.message));
  }
};

// 批量删除（删除后刷新全量数据）
const handleBatchOperate = (command) => {
  if (command === 'batchDelete') {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请选择要删除的项');
      return;
    }
    ElMessageBox.confirm(
        '此操作将永久删除选中项, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    ).then(async () => {
      try {
        const ids = selectedRows.value.map(row => row.id);
        await axios.post(`${API_BASE_URL}/employees/batch_delete/`, { ids });
        ElMessage.success('批量删除成功');
        selectedRows.value = [];
        fetchAllData();  // 重新获取全量数据
      } catch (error) {
        ElMessage.error('批量删除失败: ' + (error.response?.data?.error || error.message));
      }
    }).catch(() => {
      ElMessage.info('已取消删除');
    });
  }
};

// 编辑操作（编辑后刷新全量数据）
const handleEdit = (row) => {
  Object.assign(form, row);
  if (form.entry_time) form.entry_time = new Date(form.entry_time);
  if (form.contract_term) form.contract_term = new Date(form.contract_term);
  dialogVisible.value = true;
};

// 单个删除（删除后刷新全量数据）
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `此操作将永久删除${row.name}, 是否继续?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      await axios.delete(`${API_BASE_URL}/employees/${row.id}/`);
      ElMessage.success('删除成功!');
      fetchAllData();  // 重新获取全量数据
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.error || error.message));
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 表格选中项变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
</script>

<style scoped>
.employee-management-container {
  padding: 24px;
  background-color: #fff;
  height: 79vh;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.header-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-operation {
  display: flex;
  gap: 10px;
}

.el-table {
  --el-table-header-text-color: #333;
}

.el-pagination {
  margin-top: 20px;
}

:deep(.el-button--mini) {
  margin-right: 8px;
}
</style>